import { useState, useEffect, useCallback } from 'react';
import { getNetworks, protoGetPath } from '@/services/networks';
import { NexusServiceClient } from '@/utils/nexus_grpc_web_pb.js';
import { EmptyRequest, Network, Networks, GetPathRequest } from '@/utils/nexus_pb';

var client = new NexusServiceClient('http://localhost:8080', null, null);

function ipToInt(ip) {  
  const octets = ip.split('.');  
  if (octets.length !== 4) {  
      throw new Error('Invalid IP address');  
  }  
    
  const a = parseInt(octets[0], 10) << 24;  
  const b = parseInt(octets[1], 10) << 16;  
  const c = parseInt(octets[2], 10) << 8;  
  const d = parseInt(octets[3], 10);  
    
  return a | b | c | d;  
} 

export default function Page() {
  const [networks, setNetworks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [path, setPath] = useState([]);

  useEffect(() => {
    getNetworks().then((res) => {
      console.log(res);
      setNetworks(res);
      setLoading(false);
    });
  }, []);

  function createNetwork(
    params: {name?: string, token?: string},
    options?: { [key: string]: any },
  ) {
    return new Promise((resolve, reject) => {
      var req = new Network();
      req.setName(params.name);
      req.setToken(params.token);
  
      client.createNetwork(req, {}, (err, resp) => {
        if (err) {
          reject(err);
        } else {
          resolve(resp);
        }
      });
    });
  }

  const getPath = useCallback(
    (network, src, dip) => {
      var req = new GetPathRequest();
      req.setNetwork(network)
      req.setSource(src);
      req.setDip(ipToInt(dip));
      console.log(req)
  
      client.getPath(req, {}, (err, resp) => {
        if (err) {
          console.log(err);
        } else {
          console.log(resp.toObject().hopsList)
          setPath(resp.toObject().hopsList);
        }
      });
    },
    []
  );

  return {
    networks,
    loading,
    path,
    getPath,
  };
};